﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RegistrationDate
{
    public partial class FrmSoftReg : Form
    {
        public FrmSoftReg()
        {
            InitializeComponent();
        }

        private void FrmSoftReg_Load(object sender, EventArgs e)
        {
            
            CRegEditCtl reg = new CRegEditCtl();
            string machineCode = reg.ReadRegedit(reg.keyName, reg.keyName) as string;
            byte[] bytes = Encoding.ASCII.GetBytes(machineCode);
            string str = "";
            foreach (var b in bytes) {
                str += b.ToString("X2");
            }
            tbMachineCode.Text = str;
        }

        private void btnReg_Click(object sender, EventArgs e)
        {
            string str = tbRegCode.Text.Trim();
            if (str.Length == 0 || str.Length % 2 != 0) {
                MessageBox.Show("请输入正确的注册码");
                this.DialogResult = DialogResult.No;
                return;
            }

            string enStr = HexStr2EnStr(str);

            CRegEditCtl reg = new CRegEditCtl();
            string datetimeStr = AESModel.AESDecrypt(enStr);
            
            DateTime dt;
            try {
                dt = Convert.ToDateTime(datetimeStr);
            } catch {
                MessageBox.Show("请输入正确的注册码!");
                this.DialogResult = DialogResult.No;
                return;
            }

            string machineCodeEn = HexStr2EnStr(tbMachineCode.Text.Trim());
            string machineCode = AESModel.AESDecrypt(machineCodeEn);
            if (machineCode.Split('.')[1] != datetimeStr.Split('.')[1]) {
                MessageBox.Show("请输入正确的注册码!");
                return;
            }

            dt = DateTime.Now;
            reg.WriteRegedit(reg.keyName, reg.keyName, AESModel.AESEncrypt(dt.ToString("yyyy-MM-dd HH:mm:ss.fff")));//将注册码写入
            reg.WriteRegedit(reg.keyName, reg.regKeyName,AESModel.AESEncrypt( 0.ToString()));
            reg.WriteRegedit(reg.keyName, reg.effectiveDateName, enStr);
            this.DialogResult = DialogResult.Yes;
        }

        private string HexStr2EnStr(string hexStr) {
            string[] strs = new string[hexStr.Length / 2];
            for (int i = 0; i < strs.Length; i++) {
                strs[i] = hexStr.Substring(i * 2, 2);
            }

            byte[] bytes = new byte[strs.Length];

            for (int i = 0; i < strs.Length; i++) {
                bytes[i] = Convert.ToByte(strs[i], 16);
            }

            return Encoding.ASCII.GetString(bytes);
        }

        private void FrmSoftReg_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(this.DialogResult != DialogResult.Yes)this.DialogResult = DialogResult.No;
        }
    }
}
